package com.lyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.config.IdAutoConfiguration;
import com.lyl.domain.User;
import com.lyl.domain.UserAuthAuditRecord;
import com.lyl.dto.UserDto;
import com.lyl.geetest.GeetestLib;
import com.lyl.mapper.UserMapper;
import com.lyl.mappers.UserDtoMapper;
import com.lyl.model.AuthForm;
import com.lyl.service.UserAuthAuditRecordService;
import com.lyl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author lylbell
 * @date 2021-06-26 14:44
 */
    
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{



    @Autowired
    private UserAuthAuditRecordService userAuthAuditRecordService;

    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public User getById(Serializable id) {
        User user = super.getById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        Byte seniorAuthStatus = null;
        String seniorAuthDesc = null;
        Integer reviewsStatus = user.getReviewsStatus();//用户被审核的状态：1通过，2拒绝，3待审核
        if (reviewsStatus == null) {  //代表用户资料未上传
            seniorAuthStatus = 3;
            seniorAuthDesc = "资料未填写";
        }else {
            switch (reviewsStatus) {
                case 1 :
                    seniorAuthStatus = 1;
                    seniorAuthDesc = "审核通过";
                    break;
                case 2 :
                    seniorAuthStatus = 2;
                    List<UserAuthAuditRecord> userAuthAuditRecordList = userAuthAuditRecordService.getUserAuthAuditRecordList(user.getId());
                    if (!CollectionUtils.isEmpty(userAuthAuditRecordList)) {
                        UserAuthAuditRecord userAuthAuditRecord = userAuthAuditRecordList.get(0);
                        seniorAuthDesc = userAuthAuditRecord.getRemark();
                    }
                    seniorAuthDesc = "原因未知";
                    break;
                case 0:
                    seniorAuthStatus = 0;
                    seniorAuthDesc = "等待审核";
                    break;
            }
        }
        user.setSeniorAuthStatus(seniorAuthStatus);
        user.setSeniorAuthDesc(seniorAuthDesc);
        return user;
    }

    /**
     * 分页查找用户
     *
     * @param page
     * @param mobile   手机号
     * @param userId   用户id
     * @param userName 用户名
     * @param realName 真实姓名
     * @param status   状态
     * @return
     */
    @Override
    public Page<User> findByPage(Page<User> page, String mobile, Long userId, String userName, String realName, Integer status,Integer reviewsStatus) {
        return page(page,new LambdaQueryWrapper<User>()
                    .like(!StringUtils.isEmpty(mobile),User::getMobile,mobile)
                    .eq(userId != null,User::getId,userId)
                    .like(!StringUtils.isEmpty(userName),User::getUsername,userName)
                    .like(!StringUtils.isEmpty(realName),User::getRealName,realName)
                    .eq(status!= null,User::getStatus,status)
                    .eq(reviewsStatus!=null,User::getReviewsStatus,reviewsStatus)
        );
    }

    /**
     * 获取用户邀请列表
     *
     * @param page
     * @param userId
     * @return
     */
    @Override
    public Page<User> findDirectInvites(Page<User> page, Long userId) {
        return page(page,new LambdaQueryWrapper<User>()
                .eq(User::getDirectInviteid,userId)
        );
    }

    /**
     * 审核用户认证信息
     *
     * @param id
     * @param authStatus
     * @param authCode
     * @param remark
     * @return
     */
    @Transactional
    @Override
    public Boolean updateUserAuthStatus(Long id, Integer authStatus, Long authCode, String remark) {
        User user = getById(id);
        if (user != null) {
            user.setAuthStatus(authStatus);
            updateById(user);
        }
        UserAuthAuditRecord userAuthAuditRecord = new UserAuthAuditRecord();
        userAuthAuditRecord.setUserId(id);
        userAuthAuditRecord.setAuthCode(authCode);
        userAuthAuditRecord.setStatus(authStatus);
        userAuthAuditRecord.setRemark(remark);
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAuthAuditRecord.setAuditUserId(Long.valueOf(userId));
//        Result result = adminServerFeign.getById(id);
//        System.out.println("远程调用"+result);
//        userAuthAuditRecord.setAuditUserName(result.getData());
        return userAuthAuditRecordService.save(userAuthAuditRecord);
    }

    /**
     * 身份认证（姓名和身份证）
     *
     * @param authForm
     * @return
     */
    @Override
    public Boolean authAccount(AuthForm authForm) {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        User user = getById(Long.valueOf(userId));
        Assert.notNull(user,"认证的用户不存在");
        Integer authStatus = user.getAuthStatus();
        if (!authStatus.equals(0)) {
            throw new IllegalArgumentException("该用户已经认证成功了");
        }
        //极验验证
        AuthForm.check(authForm,geetestLib,redisTemplate);

        //阿里云身份认证
        boolean check = IdAutoConfiguration.check(authForm.getRealName(), authForm.getIdCard());
        if (!check) {
            throw new IllegalArgumentException("该用户信息错误,请检查");
        }
        user.setAuthtime(new Date());
        user.setAuthStatus(1);
        user.setRealName(authForm.getRealName());
        user.setIdCard(authForm.getIdCard());
        user.setIdCardType(authForm.getIdCardType());
        return updateById(user);
    }

    /**
     * 用于admin-server 里面远程调用member-server:查询用户的基本信息
     *
     * @param ids
     * @return
     */
    @Override
    public Map<Long,UserDto> getBasicUsers(List<Long> ids, String username, String mobile) {
        if (CollectionUtils.isEmpty(ids) && StringUtils.isEmpty(username)&&StringUtils.isEmpty(mobile)) {
            return Collections.emptyMap() ;
        }

        List<User> list = list(new LambdaQueryWrapper<User>()
                .in(!CollectionUtils.isEmpty(ids),User::getId, ids)
                .like(!StringUtils.isEmpty(username),User::getUsername,username)
                .like(!StringUtils.isEmpty(mobile),User::getMobile,mobile)

        );

        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }

        List<UserDto> userDtos = UserDtoMapper.INSTANCE.convert2Dto(list);
        Map<Long, UserDto> map = userDtos.stream().collect(Collectors.toMap(UserDto::getId, userDto -> userDto));
        return map;
    }
}
